<template>
	<DragResize
		v-if="widgetVisible"
		:is-active="!isSelectMode ? widget.active : widget.activeForPicker"
		:data-id="widget.id"
		:widget="widget"
		:parent-w="parentWH.parentW"
		:parent-h="parentWH.parentH"
		:init-rect="widget.rect"
		:minh="0"
		:minw="0"
		:grid-x="1"
		:grid-y="1"
		:stick-size="5"
		:snap-to-grid="true"
		:parent-limitation="true"
		:prevent-active-behavior="true"
		:draggable="widgetDraggable"
		:resizable="widgetResizable"
		:droppable="widgetDroppable"
		:selectable="widgetSelectable"
		:is-locked="widget.isLocked"
		:is-freeze="widget.isFreeze"
		:throttle="false"
		:style="styles"
		class="position-absolute box-sizing-border"
		@clicked="onClicked"
		@dblclick.native="doubleClickWidget"
		@dragging="dragging"
		@dragstop="dragStop">
		<Widget
			v-for="child in widget.children"
			:key="child.id"
			:widget="child"
			:is-multi-mode="isMultiMode"
			:is-select-mode="isSelectMode"></Widget>
		<i
			v-if="isMultiMode && widget.active"
			:class="widget.isLocked ? 'icon-shangsuo font-color-danger' : 'icon-qiyong font-color-primary'"
			class="iconfont widget-select-mark"></i>
	</DragResize>
</template>

<script>
	import DragResize from '../../DragResize';
	import {deepCopy, formatColor} from '@/utils';
	import {assetBaseUrl} from '@/config/env';
	import {mapState} from 'vuex';
	import {generateWidgetHash, getBasicStyles, widgetHashKeys} from '@/modules/IDE/widget/atom/widget';
	import {WidgetDevice} from "@/modules/IDE/widget/atom/widgetDevice";
	import {WidgetFactory} from "@/modules/IDE/widgetFactory";

	export default {
		name: 'DeviceWidget',
		components: {
			DragResize,
			'Widget': () => import("@/components/IDE/widget/atom/Widget.vue")
		},
		props: {
			widget: {
				type: WidgetDevice,
				default: () => {
					return {};
				}
			},
			isMultiMode: {
				type: Boolean,
				default: false
			},
			isSelectMode: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				widgetChangeHandler: () => {
				},
			};
		},
		computed: {
			...mapState({
				freezeMode: state => state.ide.freezeMode,
				activeTheme: state => state.ide.activeTheme,
			}),
			computedWidget() {
				const widget = {};
				// 过滤出关心变更的属性，并进行深拷贝
				widgetHashKeys.forEach(key => widget[key] = this.widget[key]);
				return widget;
			},
			widgetVisible() {
				if (this.widget.isDeleted) return false;
				return !this.isSelectMode ? this.widget.display : this.widget.displayForPicker;
			},
			widgetDraggable() {
				if (this.freezeMode) return false;
				if (this.isSelectMode) return false;
				if (this.belongNotMatch) return false;
				return this.widget.draggable;
			},
			widgetResizable() {
				if (this.freezeMode) return false;
				if (this.isSelectMode) return false;
				if (this.belongNotMatch) return false;
				return this.widget.resizable;
			},
			widgetDroppable() {
				if (this.freezeMode) return false;
				if (this.isSelectMode) return false;
				if (this.belongNotMatch) return false;
				return this.widget.droppable;
			},
			widgetSelectable() {
				if (this.belongNotMatch) return false;
				if (this.isSelectMode) return true;
				return this.widget.selectable;
			},
			// 传父组件宽高
			parentWH() {
				const parentWidget = WidgetFactory.getWidgetById(this.widget.parentId) || null;
				return {
					'parentW': parentWidget ? parentWidget.rect.width : 0,
					'parentH': parentWidget ? parentWidget.rect.height : 0
				}
			},
			belongNotMatch() {
				// 判断组件从属是否匹配，主页中应用的子页，只有在编辑子页时才能更改
				const curPageType = !this.isSelectMode ? this.curPageType : this.curPageTypeForPicker;
				return curPageType === 'page' && !!this.widget.subPageId;
			},
			styles() {
				if (!this.widget || !this.widget.UI.state) return;
				const styles = {};

				// 如果小组件正在被拖拽，则设置组件透明度
				styles.opacity = this.widget.isDragging ? 0.8 : 1;

				const {backStyle = {}} = this.widget.getCurrentState();
				const {
					border = {},
					shadow = {},
					borderRadius = {},
					backgroundColor = '#FFFFFF',
					backgroundImage = ''
				} = backStyle

				// 基础样式
				const basicStyles = getBasicStyles(this.widget.getCurrentState());
				// 修改背景

				styles.backgroundColor = formatColor(backgroundColor, this.activeTheme);
				// 修改文字
				//  textStyle &&  styles.color = this.formatColor(textStyle.color);
				//修改边框
				const {
					top: bTop = {}, left: bLeft = {}, bottom: bBottom = {}, right: bRight = {}
				} = border;
				const {width: btWidth = 0, color: btColor = ''} = bTop;
				const {width: blWidth = 0, color: blColor = ''} = bLeft;
				const {width: bbWidth = 0, color: bbColor = ''} = bBottom;
				const {width: brWidth = 0, color: brColor = ''} = bRight;
				styles.borderColor = formatColor(border.color, this.activeTheme);
				btWidth && btColor && (basicStyles.borderTop = `${btWidth}px ${formatColor(btColor, this.activeTheme)} solid`)
				blWidth && blColor && (basicStyles.borderLeft = `${blWidth}px ${formatColor(blColor, this.activeTheme)} solid`);
				bbWidth && bbColor && (basicStyles.borderBottom = `${bbWidth}px ${formatColor(bbColor, this.activeTheme)} solid`);
				brWidth && brColor && (basicStyles.borderRight = `${brWidth}px ${formatColor(brColor, this.activeTheme)} solid`);
				// 修改阴影
				const {xOffset = 0, yOffset = 0, blur = 0, spread = 0, color = '', type = ''} = shadow;
				color && (basicStyles.boxShadow = `${xOffset}px ${yOffset}px ${blur}px ${spread}px ${formatColor(color, this.activeTheme)} ${type}`);
				// 背景图片
				if (backgroundImage) {
					styles.backgroundImage = `url(${assetBaseUrl}/file/download/${backgroundImage})`;
					styles.backgroundSize = 'cover';
					styles.backgroundPosition = 'center';
					styles.backgroundRepeat = 'no-repeat';
				}
				switch (this.widget.category) {
				  case 'image':
					  if (!backgroundImage) {
						  styles.backgroundImage = `url(${require('@/assets/img/empty-state.png')})`;
						  styles.backgroundSize = 'cover';
						  styles.backgroundPosition = 'center';
						  styles.backgroundRepeat = 'no-repeat';
					  }
				    break;
				  case 'circleClock':
					  if (!backgroundImage) {
						  styles.backgroundImage = `url(${require('@/assets/img/clock.png')})`;
						  styles.backgroundSize = 'cover';
						  styles.backgroundPosition = 'center';
						  styles.backgroundRepeat = 'no-repeat';
					  }
				    break;
				  case 'calendar':
					  if (!backgroundImage) {
						  styles.backgroundImage = `url(${require('@/assets/img/calendar.jpeg')})`;
						  styles.backgroundSize = '100% 100%';
						  styles.backgroundPosition = 'center';
						  styles.backgroundRepeat = 'no-repeat';
					  }
				    break;
				  case 'qrCode':
					  if (!backgroundImage) {
						  styles.backgroundImage = `url(${require('@/assets/img/qrCode.png')})`;
						  styles.backgroundSize = 'contain';
						  styles.backgroundPosition = 'center';
						  styles.backgroundRepeat = 'no-repeat';
					  }
				    break;
				  case 'scroll':
					  if (this.widget.UI.data.scrollDirection === 'horizontal') {
						  styles.overflowX = 'scroll';
						  styles.overflowY = 'hidden';
					  } else {
						  styles.overflowY = 'scroll';
						  styles.overflowX = 'hidden';
					  }
				    break;
				  default:
				    break;
				}
				// 圆角
				const {
					width: brgWidth = 0,
					topLeft = 0,
					topRight = 0,
					bottomLeft = 0,
					bottomRight = 0,
				} = borderRadius;
				if (brgWidth) {
					borderRadius.topLeft = brgWidth;
					borderRadius.topRight = brgWidth;
					borderRadius.bottomLeft = brgWidth;
					borderRadius.bottomRight = brgWidth;
				}
				topLeft && (styles.borderTopLeftRadius = `${topLeft}px`);
				topRight && (styles.borderTopRightRadius = `${topRight}px`);
				bottomLeft && (styles.borderBottomLeftRadius = `${bottomLeft}px`);
				bottomRight && (styles.borderBottomRightRadius = `${bottomRight}px`);
				return {...styles, ...basicStyles};
			},
			showMask() {
				if (this.widget.type !== 'atomic') return false;
				const containers = [
					'container', 'tabBarPage', 'scroll', 'listCell',
					'listView', 'webView', 'gridView', 'buttonList','dragLayout'
				];
				return !containers.includes(this.widget.category);
			},
		},
		watch: {
			computedWidget: {
				handler(widget) {
					if (this.isSelectMode) return;
					this.widgetChangeHandler(widget);
				},
				deep: true,
			},
			'widget.rect': {
				handler(rect = {}) {
					this.widget.tempRect = deepCopy(rect);
				},
				deep: true,
				immediate: true
			}
		},
		created() {
			// 注意：watch 中使用防抖动，防抖动方法需要定义在 data 中，不能写在 methods 中，
			// 因为当页面有多个 widget 实例时，会导致防抖逻辑不独立，造成防抖不能正常生效
			this.widgetChangeHandler = _.debounce((newWidget) => {
				this.widget.curHash = generateWidgetHash(newWidget);
			}, 300);
		},
		methods: {
			onClicked() {
				if (!this.isSelectMode) {
					if (!this.widget.selectable) return;
					this.$EventBus.$emit('selectWidget', this.widget);
				} else {
					this.$EventBus.$emit('selectWidgetForPicker', this.widget);
				}
			},
			doubleClickWidget(event) {
				!this.belongNotMatch && event.stopPropagation();
				if (!this.isSelectMode || this.belongNotMatch) return;
				this.$EventBus.$emit('dbClickWidgetForPicker', this.widget);
			},
			dragging(rect = {}) {
				this.widget.isDragging = true;
				const {left = 0, top = 0, width = 0, height = 0} = rect;
				this.widget.tempRect = {left, top, width, height};
				this.$emit('dragging', this.widget);
			},
			dragStop() {
				this.widget.isDragging = false;
				this.$emit('dragStop', this.widget);
			},
		}
	};
</script>

<style lang="less" scoped>

</style>
